<?php
/**
 * 	app后台登录
 *  =============================
 *	Author: 褚天恩
 *  Date: 2019-04-23
 */
namespace app\walletyhbbadmin\controller;
use think\Controller;
use think\Db;
use think\Session;
class Login extends Controller{
   	
	/**
	 * 登录页面
	 */
    public function index(){
    	return $this->fetch();
    }
    /**
     * 登录验证
     */
    public function checkLogin(){
    	$username = trim(input('username'));
    	$pwd = trim(input('pwd'));
    	//验证输入信息
    	if(empty($username)||empty($pwd)){
    		$data['info'] = '请填写完整信息';
    		$data['status'] = -2;
    		return json($data);
    	}
    	$admin = Db::name("Admin")->where(array('user_name'=>$username))->find();
    	if($admin['password']!= md5($pwd) ){
    		$data['info'] = '登录密码不正确';
    		$data['status'] = -1;
    		return json($data);
    	}else{
    	    $arr = DB::name('Admin')->where(['admin_id'=>$admin['admin_id']])->find();
    	    $save['before_login'] = $arr['last_login'];
    		$save['last_ip'] = $this->ip();
    		$save['last_login'] = time();
    		Db::name('Admin')->where(['admin_id'=>$admin['admin_id']])->update($save);
    		$data['login_time'] = time();
    		$data['log_ip'] = $this->ip();
    		$data['log_url'] = $_SERVER['REQUEST_URI'];
    		$data['log_info'] = '后台登录';
    		$data['admin_id'] = $admin['admin_id'];
    		$data['log_time'] = time();
    		Db::name('Admin_log')->where(['admin_id'=>$admin['admin_id']])->insert($data);
    		session('admin_id',$admin['admin_id']);
    		$data['info'] = '登录成功';
    		$data['status'] = 1;
    		return json($data);
    	}
    }
    public function ip() {
    	//strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
    	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
    		$ip = getenv('HTTP_CLIENT_IP');
    	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
    		$ip = getenv('HTTP_X_FORWARDED_FOR');
    	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
    		$ip = getenv('REMOTE_ADDR');
    	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
    		$ip = $_SERVER['REMOTE_ADDR'];
    	}
    	$res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    	return $res;
    
    }
    /**
     * 安全退出
     */
    public function loginout(){
    	session('admin_id', null);
    	$this->redirect('Login/index');
    }
}